<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Search, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CommonHeader from '@/components/CommonHeader.vue'
import CommonFooter from '@/components/CommonFooter.vue'
import FloatingSidebar from '@/components/FloatingSidebar.vue'
import { getParentCategoryService, getCategoryListVO, searchProductService } from '@/api/product.js'

const router = useRouter()

const route = useRoute()

const loading = ref(false)

// 排序方式，默认显示"默认排序"
const sortBy = ref('default')
// 商品分类，默认显示"全部"
const category = ref('')

// 是否显示搜索历史和热门搜索区域
const showSearchSections = ref(true)
// 是否已经执行过搜索
const searchPerformed = ref(false)
// 控制"更多筛选"弹窗显示
const showMoreFiltersDialog = ref(false)

// 搜索历史
const searchHistory = ref([])
// 热搜
const hotSearches = ref([])
// 筛选
const showFilters = computed(() => searchQuery.value.keyword && searchQuery.value.keyword.trim() !== '' && searchPerformed.value)

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const categories = ref([])
const products = ref([])

// 搜索输入框绑定的内容
const searchQuery = ref({})
const lastKeyword = ref('')

// 搜索
const handleSearch = async (isNewSearch = false) => {
  if (!searchQuery.value.keyword || !searchQuery.value.keyword.trim()) return

  // 只有当关键词变化时才重置分类和排序
  if (searchQuery.value.keyword.trim() !== lastKeyword.value) {
    category.value = ''
    sortBy.value = 'default'
  }

  if (isNewSearch) {
    currentPage.value = 1 
    router.replace({
      query: { ...route.query, q: searchQuery.value.keyword.trim() }
    })
  }

  // 同步排序和分类参数
  searchQuery.value.type = sortBy.value
  searchQuery.value.categoryId = category.value

  loading.value = true
  showSearchSections.value = false
  searchPerformed.value = true

  const result = await searchProductService(searchQuery.value)
  products.value = result.data.list;
  total.value = parseInt(result.data.total);

  if (!searchHistory.value.includes(searchQuery.value.keyword)) {
    searchHistory.value.unshift(searchQuery.value.keyword)
    if (searchHistory.value.length > 10) {
      searchHistory.value.pop()
    }
  }

  loading.value = false

  // 更新 lastKeyword
  lastKeyword.value = searchQuery.value.keyword.trim()
}

// 每页展示记录数变化
const handleSizeChange = (val) => {
    // 同步更新 pageSize
    pageSize.value = val;
    // 同步更新搜索参数
    searchQuery.value.pageSize = val;
    handleSearch();
}
// 页码变化时触发
const handleCurrentChange = (val) => {
    // 同步更新 currentPage
    currentPage.value = val;
    // 同步更新搜索参数
    searchQuery.value.pageNum = val;
    handleSearch();
}
// 获取分类列表
const getCategoryList = async () => {
  const result = await getParentCategoryService()
  categories.value = Array.isArray(result.data) ? result.data : []
}

// 监听路由参数变化
watch(() => route.query.q, (newQuery) => {
  if (newQuery) {
    searchQuery.value.keyword = newQuery
    handleSearch(true)
  }
}, { immediate: true })

const handleTagSearch = (tag) => {
  searchQuery.value.keyword = tag
  handleSearch(true)
}

const handleHistoryClose = (tag) => {
  searchHistory.value = searchHistory.value.filter(item => item !== tag)
  ElMessage.success(`已移除搜索历史: ${tag}`)
}
// 删除所有搜索历史
const clearHistory = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有搜索历史吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    searchHistory.value = []
    ElMessage.success('已清空搜索历史')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空失败，请稍后重试')
    }
  }
}

// 跳转到商品详情页
const viewProduct = (productId) => {
  router.push(`/home/product/${productId}`)
}

// 提示信息
const handleMoreFiltersClick = () => {
  ElMessageBox.alert(
    '该功能目前尚在开发阶段，尚未完成全部的构建与优化工作。我们正在对其进行深入的设计与调试，以确保其能够稳定、高效地运行。在正式发布之前，还需要经过多轮测试和不断完善，以达到最佳的用户体验。敬请期待后续进展。',
    '提示',
    {
      confirmButtonText: '我知道了',
      type: 'info',
      showClose: false
    }
  )
  // showMoreFiltersDialog.value = true // 保留原有弹窗逻辑但不弹出
}

// 页面加载完成
onMounted(() => {
  
  getCategoryList()
})

</script>

<template>
  <div class="main-layout">
    <CommonHeader />
    <FloatingSidebar />

    <div class="search-view">

      <div class="search-header">
        <div class="search-input-wrapper">
          <el-input v-model="searchQuery.keyword" placeholder="搜索商品" :prefix-icon="Search" class="search-input"
            @keyup.enter="handleSearch(true)">
            <template #append>
              <el-button @click="handleSearch(true)">搜索</el-button>
            </template>
          </el-input>
        </div>
      </div>
      <!-- 筛选 -->
      <div class="search-filters">
        <el-select v-model="sortBy" placeholder="排序方式" @change="handleSearch">
          <el-option label="默认排序" value="default" />
          <el-option label="价格从低到高" value="price_asc" />
          <el-option label="价格从高到低" value="price_desc" />
          <el-option label="销量优先" value="sales" />
        </el-select>

        <el-select
          v-model="category"
          placeholder="商品分类"
          @change="handleSearch"
        >
          <el-option label="全部" :value="''" />
          <el-option
            v-for="cat in categories"
            :key="cat.id"
            :label="cat.name"
            :value="cat.id.toString()"
          />
        </el-select>

        <el-button @click="handleMoreFiltersClick">更多筛选</el-button>
      </div>
      <!-- 搜索历史 -->
      <div class="search-sections" v-if="showSearchSections">
        <div class="search-section" v-if="searchHistory.length > 0">
          <h3 class="section-title">搜索历史
            <el-button link type="primary" @click="clearHistory">清空</el-button>
          </h3>
          <div class="tags-container">
            <el-tag v-for="tag in searchHistory" :key="tag" closable :disable-transitions="false"
              @click="handleTagSearch(tag)" @close="handleHistoryClose(tag)" class="search-tag">
              {{ tag }}
            </el-tag>
          </div>
        </div>
    
        <div class="search-section">
          <h3 class="section-title">热门搜索</h3>
          <div class="tags-container hot-searches-tags-container">
            <el-tag v-for="tag in hotSearches" :key="tag" :disable-transitions="false" @click="handleTagSearch(tag)"
              type="info" class="search-tag hot-tag">
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </div>
      <!-- 搜索结果 -->
      <div class="search-results" v-loading="loading">
        <el-empty v-if="!loading && products.length === 0" description="暂无搜索结果" />
        <div v-else class="product-grid">
          <el-card v-for="product in products" :key="product.id" class="product-card" @click="viewProduct(product.id)">
            <img :src="product.image" class="product-image" />
            <div class="product-info">
              <div class="product-info-row">
                <h3 class="product-title">{{ product.name }}</h3>
                <p class="product-price">
                  ¥{{ product.price }}
                  <span v-if="product.originalPrice && product.originalPrice > product.price" class="product-original-price">¥{{ product.originalPrice }}</span>
                </p>
              </div>
              <div class="product-meta">
                <span class="product-sales">销量: {{ product.sold }}</span>
                <span class="product-comment">评价: {{ product.commentCount }}</span>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      
  
              <!-- 分页 -->
              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="currentPage" 
                  v-model:page-size="pageSize"
                  :page-sizes="[10, 20, 50]"
                  size="default" 
                  :background="true"
                  layout="total, sizes, prev, pager, next, jumper" 
                  :total="total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange" />
              </div>



      <!-- 关闭功能 -->
      <el-dialog v-model="showMoreFiltersDialog" title="更多筛选" width="50%">
        <div>
          <h3 class="filter-section-title">物流</h3>
          <div class="button-group">
            <el-button :class="{ 'is-active': selectedLogistics === '包邮' }"
              @click="selectedLogistics = '包邮'">包邮</el-button>
            <el-button :class="{ 'is-active': selectedLogistics === '退货宝' }"
              @click="selectedLogistics = '退货宝'">退货宝</el-button>
          </div>
        </div>

        <div>
          <h3 class="filter-section-title">店铺评分</h3>
          <div class="button-group">
            <el-button :class="{ 'is-active': selectedStoreRating === '4.8分及以上 优秀' }"
              @click="selectedStoreRating = '4.8分及以上 优秀'">4.8分及以上 优秀</el-button>
            <el-button :class="{ 'is-active': selectedStoreRating === '4.6分及以上 良好' }"
              @click="selectedStoreRating = '4.6分及以上 良好'">4.6分及以上 良好</el-button>
          </div>
        </div>

        <div>
          <h3 class="filter-section-title">价格区间</h3>
          <div class="price-range-inputs">
            <el-input placeholder="自定义最低价" style="width: 120px; margin-right: 10px;"></el-input> -
            <el-input placeholder="自定义最高价" style="width: 120px; margin-left: 10px;"></el-input>
          </div>
        </div>

        <div>
          <h3 class="filter-section-title">发货地</h3>
          <div class="location-buttons button-group">
            <el-button :class="{ 'is-active': selectedLocation === '北海' }"
              @click="selectedLocation = '北海'">北海</el-button>
            <el-button :class="{ 'is-active': selectedLocation === '江浙沪' }"
              @click="selectedLocation = '江浙沪'">江浙沪</el-button>
            <el-button :class="{ 'is-active': selectedLocation === '珠三角' }"
              @click="selectedLocation = '珠三角'">珠三角</el-button>
            <el-button :class="{ 'is-active': selectedLocation === '港澳台' }"
              @click="selectedLocation = '港澳台'">港澳台</el-button>
            <el-button :class="{ 'is-active': selectedLocation === '海外' }"
              @click="selectedLocation = '海外'">海外</el-button>
            <el-button icon="LocationMarker" link>重新定位</el-button>
            <el-button>更多 <el-icon>
                <ArrowDown />
              </el-icon></el-button>
          </div>
        </div>

        <div>
          <h3 class="filter-section-title">其他</h3>
          <div class="other-buttons button-group">
            <el-button :class="{ 'is-active': selectedOther === '天猫' }" @click="selectedOther = '天猫'">天猫</el-button>
            <el-button :class="{ 'is-active': selectedOther === '公益宝贝' }"
              @click="selectedOther = '公益宝贝'">公益宝贝</el-button>
            <el-button :class="{ 'is-active': selectedOther === '关闭个性化' }"
              @click="selectedOther = '关闭个性化'">关闭个性化</el-button>
          </div>
          <el-form label-width="100px" class="other-filters-form">
            <el-form-item label="品牌">
              <el-input placeholder="请输入品牌"></el-input>
            </el-form-item>
            <el-form-item label="库存数量">
              <el-input placeholder="请输入库存数量"></el-input>
            </el-form-item>
            <el-form-item label="属性">
              <el-checkbox-group>
                <el-checkbox label="颜色" />
                <el-checkbox label="尺寸" />
                <el-checkbox label="材质" />
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showMoreFiltersDialog = false">取消</el-button>
            <el-button type="primary" @click="showMoreFiltersDialog = false">确定</el-button>
          </span>
        </template>
      </el-dialog>

    </div>
    <CommonFooter />
  </div>
</template>

<style scoped>
.search-view {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.search-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

.search-input-wrapper {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  display: block;
}

.search-input {
  height: 65px;
  font-size: 24px;
}

.search-input .el-input__wrapper {
  padding: 12px 15px;
}

.search-input .el-input-group__append {
  padding: 0 28px;
  font-size: 24px;
}

.search-input .el-input__inner {
  height: 100%;
}

.search-filters {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}

.search-sections {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.search-section {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  width: 100%;
  max-width: 1400px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  width: 100%;
}

.search-tag {
  cursor: pointer;
  transition: all 0.2s ease;
}

.search-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.hot-tag {
  background-color: #f0f2f5;
  color: #606266;
  border-color: #dcdfe6;
}

.hot-tag:hover {
  background-color: #e4e7ed;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.product-card {
  cursor: pointer;
  transition: transform 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 10px;
}

.product-title {
  margin: 0;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
}

.product-original-price {
  color: #aaa;
  text-decoration: line-through;
  font-size: 14px;
  margin-left: 8px;
}

.product-meta {
  display: flex;
  gap: 16px;
  color: #909399;
  font-size: 14px;
  margin: 0;
  margin-top: 4px;
}
.product-meta .product-sales,
.product-meta .product-comment {
  margin: 0;
  padding: 0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 32px 0 24px 0;
  padding: 20px 0;
}

:deep(.el-pagination) {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  padding: 16px 24px;
  border: 1px solid #e4e7ed;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 8px;
  margin: 0 4px;
  transition: all 0.3s ease;
  font-weight: 500;
  min-width: 36px;
  height: 36px;
  line-height: 36px;
}

:deep(.el-pagination .el-pager li.active) {
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: #fff;
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

:deep(.el-pagination .el-pager li:hover) {
  background: #ecf5ff;
  color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

:deep(.el-pagination .el-pagination__sizes .el-select .el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
}

:deep(.el-pagination .el-pagination__jump) {
  margin-left: 16px;
}

:deep(.el-pagination .el-pagination__total) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-pagination .btn-prev:hover),
:deep(.el-pagination .btn-next:hover) {
  background: #ecf5ff;
  color: #409eff;
  transform: translateY(-1px);
}

:root.dark :deep(.el-pagination) {
  background: #2b2b2b;
  box-shadow: 0 4px 12px rgba(0,0,0,0.3);
  border-color: #3a3a3a;
}

:root.dark :deep(.el-pagination .el-pager li.active) {
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: #fff;
}

:root.dark :deep(.el-pagination .el-pager li:hover) {
  background: #333333;
  color: #409eff;
}

:root.dark :deep(.el-pagination .el-pagination__total) {
  color: #e0e0e0;
}

/* Dark mode styles */
:root.dark .product-card {
  background-color: #2b2b2b;
  border-color: #3a3a3a;
}

:root.dark .product-title {
  color: #ffffff;
}

:root.dark .product-sales {
  color: #909399;
}

.more-filters-content {
  display: flex;
}

.filter-sidebar {
  width: 150px;
  border-right: 1px solid #eee;
  padding-right: 20px;
}

.sidebar-item {
  padding: 10px 0;
  cursor: pointer;
  font-size: 16px;
  color: #606266;
  border-left: 3px solid transparent;
  transition: all 0.2s ease;
}

.sidebar-item:hover {
  color: #409eff;
}

.sidebar-item.active {
  color: #409eff;
  font-weight: bold;
  border-left-color: #409eff;
  background-color: #ecf5ff;
}

.filter-main-content {
  flex: 1;
  padding-left: 20px;
}

.filter-section-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.button-group .el-button {
  background-color: #f0f2f5;
  border-color: #dcdfe6;
  color: #606266;
  border-radius: 4px;
  padding: 8px 15px;
  height: auto;
  min-height: unset;
}

.button-group .el-button:hover,
.button-group .el-button.is-active {
  background-color: #e4e7ed;
  border-color: #cdd0d6;
  color: #409eff;
}

.price-range-inputs {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.location-buttons {
  /* Add specific styling for location buttons if needed */
}

.other-buttons {
  /* Add specific styling for other buttons if needed */
}

.other-filters-form .el-form-item {
  margin-bottom: 15px;
  /* Add some spacing between form items */
}

/* Dark mode styles for dialog */
:root.dark .el-dialog {
  background-color: #1a1a1a;
  border-color: #3a3a3a;
}

:root.dark .el-dialog__title {
  color: #ffffff;
}

:root.dark .el-form-item__label {
  color: #e0e0e0;
}

:root.dark .el-input__wrapper {
  background-color: #2b2b2b;
  border-color: #3a3a3a;
}

:root.dark .el-input__inner {
  color: #ffffff;
}

:root.dark .el-button {
  background-color: #3a3a3a;
  color: #e0e0e0;
  border-color: #4a4a4a;
}

:root.dark .el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

:root.dark .filter-sidebar {
  border-right-color: #3a3a3a;
}

:root.dark .sidebar-item {
  color: #e0e0e0;
}

:root.dark .sidebar-item:hover {
  color: #409eff;
}

:root.dark .sidebar-item.active {
  color: #409eff;
  border-left-color: #409eff;
  background-color: #333333;
}

:root.dark .filter-section-title {
  color: #ffffff;
  border-bottom-color: #3a3a3a;
}

::v-deep(.category-select-popper .category-grid) {
  display: flex;
  flex-wrap: wrap;
  min-width: 320px;
  padding: 8px;
}
::v-deep(.category-select-popper .category-grid-item) {
  width: 25%;
  padding: 8px 0;
  text-align: center;
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.2s, color 0.2s;
}
::v-deep(.category-select-popper .category-grid-item.active) {
  background: #409eff;
  color: #fff;
}
::v-deep(.category-select-popper .category-grid-item:hover) {
  background: #ecf5ff;
}
</style>